package com.sys.basics.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class YmlUtils {

    public static final String DEFAULT_YML = "application.yml";

    private static Map<String, String> appConfigs = new HashMap<>();

    static {
        appConfigs = parseYmlFile(DEFAULT_YML);
    }

    public static String get(String key) {
        return get(key, "");
    }

    public static String get(String key, String defaultValue) {
        return appConfigs.getOrDefault(key, defaultValue);
    }

    public static Map<String, Object> getJson() {
        return parseYmlFileJson(DEFAULT_YML);
    }

    /**
     * 根据文件名获取yml的文件内容
     * @return
     */
    public static Map<String, String> parseYmlFile(String file) {
        Map<String, String> resultMap = new HashMap<>();
        if (file == null) {
            return resultMap;
        }
        InputStream in = YmlUtils.class.getClassLoader().getResourceAsStream(file);
        Yaml yaml = new Yaml();
        Map<String, String> mapDatas = yaml.loadAs(in, Map.class);

        for (Map.Entry<String, String> entry : mapDatas.entrySet()) {
            String key = entry.getKey();
            Object val = entry.getValue();
            if (val instanceof Map) {
                Map<String, String> childResult = parseChildNode(key, (Map<String, Object>) val);
                resultMap.putAll(childResult);
            } else {
                resultMap.put(key, val.toString());
            }
        }
        return resultMap;
    }

    /**
     * 获取json结果
     * @return
     */
    public static Map<String, Object> parseYmlFileJson(String file) {
        InputStream in = YmlUtils.class.getClassLoader().getResourceAsStream(file);
        Yaml yaml = new Yaml();
        Map<String, Object> map = (Map<String, Object>) yaml.load(in);
        JSONObject jsonObject = new JSONObject(map);
        return jsonObject;
    }

    /**
     * 遍历yml文件，获取map集合
     * @param parentKey
     * @param childNode
     * @return
     */
    public static Map<String, String> parseChildNode(String parentKey, Map<String, Object> childNode) {
        Map<String, String> resultMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : childNode.entrySet()) {
            String key = entry.getKey();
            Object val = entry.getValue();

            if (StringUtils.isNotBlank(parentKey)) {
                key = parentKey + "." + key;
            }

            if (val instanceof Map) {
                Map<String, String> childResult = parseChildNode(key, (Map<String, Object>) val);
                resultMap.putAll(childResult);
            } else {
                resultMap.put(key, val.toString());
            }
        }
        return resultMap;
    }

}
